package com.questionGenerator.service.Impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.questionGenerator.dto.req.GeneratorReqDTO;
import com.questionGenerator.dto.resp.QuestionRespDTO;
import com.questionGenerator.service.GeneratorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class GeneratorServiceImpl implements GeneratorService {
    @Value("${QwenApiKey}")
    private String apiKey;
    @Override
    public QuestionRespDTO ExampleGenerator(GeneratorReqDTO generatorReqDTO) throws NoApiKeyException, InputRequiredException {
        String questionJson = getQuestionByModel(generatorReqDTO);
        log.info(questionJson);
        //使用正则表达式提取信息
        String patternString = "题目：([\\s\\S]*?)答案：([\\s\\S]*)";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(questionJson);
        //查找question和answer
        String question,answer;
        if (matcher.find()) {
             question = matcher.group(1);
             answer = matcher.group(2);
        } else {
            question = "未能匹配到生成的题目";
            answer = "未能匹配到生成的答案";
        }
        QuestionRespDTO questionRespDTO = QuestionRespDTO.builder()
                .id(-1)
                .content(question)
                .answer(answer)
                .knowledgePoint(generatorReqDTO.getKnowledgePoint())
                .type(generatorReqDTO.getType())
                .typeId(-1)
                .language(generatorReqDTO.getLanguage())
                .build();
        return questionRespDTO;
    }
    private String getQuestionByModel(GeneratorReqDTO generatorReqDTO) throws NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        String prompt = "请出一道难度为"+generatorReqDTO.getLevel()+"的编程题目"+
                "，相关知识点为"+generatorReqDTO.getKnowledgePoint()+
                "，题目类型为"+generatorReqDTO.getType()+
                "，相关的编程语言为"+generatorReqDTO.getLanguage()+
                "，请按照“题目：答案：”的形式给出题目的题干以及答案";
        log.info(prompt);
        GenerationParam param = GenerationParam.builder()
                .model("qwen-turbo")
                // 如果您没有设置环境变量，则在此处您的APIKEY即可
                .apiKey(apiKey)
                .prompt(prompt)
                .build();
        GenerationResult result = gen.call(param);
        return result.getOutput().getText();
    }
}
